<?php

namespace App\Job;

use App\Models\WechatUser;
use App\Service\WechatFactory;
use Carbon\Carbon;
use EasyWeChat\Kernel\Messages\Text;
use Hyperf\AsyncQueue\Job;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\Collection;
use Psr\Log\LoggerInterface;

/**
 * 推送关注
 * Class ScanActivitiesToBePushedJob
 * @package App\Jobs
 */
class PushAttentionJob extends Job
{
    /**
     * @var LoggerInterface
     */
    protected $logger;

    /**
     * @Inject()
     * @var WechatFactory
     */
    protected $wechatFactory;

    public function __construct(LoggerFactory $loggerFactory)
    {
        $this->logger = $loggerFactory->get('log', 'default');
    }

    public function handle()
    {
        try {
            $now = Carbon::now();
            $this->logger->info(sprintf('推送关注第%s批次', $now->format('Y-m-d H:i')));
            $twentyFourHourLimit = (clone $now)->subHours(24)->format('Y-m-d H:i') . ':00';
            $fourtyEightHourLimit = (clone $now)->subHours(48)->format('Y-m-d H:i') . ':00';

            Db::beginTransaction();

            $app = $this->wechatFactory->officialAccount(false);
            WechatUser::query()
                ->withoutGlobalScope('orderByCreatedAtDesc')
                ->where('receive_last_message', '<=', $twentyFourHourLimit) // 超过 24 小时没有回复过
                ->where('receive_last_message', '>', $fourtyEightHourLimit) // 过滤掉 超过 48 小时的会话
                ->select(['id', 'openid', 'receive_last_message', 'sent_last_remind_message'])
                ->chunk(500, function (Collection $result) use ($app, $now) {
                    try {
                        $updateSentLastRemindMessageIds = []; // 需要更新发送时间的 ID
                        $result
                            ->filter(function ($item) {
                                // 接收最后一条的时间 大于 发送最后一条的时间, 说明 24 小时内没有给用户推送过提醒
                                return ($item['receive_last_message'] > $item['sent_last_remind_message']) || ($item['sent_last_remind_message'] === null);
                            })
                            ->each(function ($item) use ($app, $now, &$updateSentLastRemindMessageIds) {
                                $message = new Text('您已经超过24小时没和系统互动了，为了保证后续素材能及时到达，请点击【立即签到】或回复关键字【获取素材】进行签到。');
                                if (Carbon::parse($item['receive_last_message'])->addHours(48)->subMinute()->isSameAs('Y-m-d H:i', $now)) {
                                    $message = new Text('您已经超过48小时未与系统互动，素材推送服务关闭，请点击【立即签到】或回复关键字【获取素材】进行签到。');
                                }

                                $app->customer_service->message($message)->to($item['openid'])->send();
                                $updateSentLastRemindMessageIds[] = $item['id'];
                            });
                        if (!empty($updateSentLastRemindMessageIds)) {
                            WechatUser::query()->whereIn('id', $updateSentLastRemindMessageIds)->update(['sent_last_remind_message' => $now]);
                        }
                    } catch (\Exception $e) {
                        $this->logger->error('推送关注信息批次发生错误: ' . $e->getMessage());
                    }
                });

            Db::commit();
        } catch (\Exception $e) {
            Db::rollBack();
            $this->logger->error('推送关注信息发生错误: ' . $e->getMessage());
        }
    }
}
